<?php
use think\Db;
require_once (EXTEND_PATH.'phpqrcode/phpqrcode.php');
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 生成国际标准ISO 8601日期和时间
 * @param $time
 * @return string
 */
function gmt_iso8601($time) {
	$dtStr = date("c", $time);
	$mydatetime = new DateTime($dtStr);
	$expiration = $mydatetime->format(DateTime::ISO8601);
	$pos = strpos($expiration, '+');
	$expiration = substr($expiration, 0, $pos);
	return $expiration."Z";
}

//换算时间
function conversionTime($time) {
    $time = (int) substr($time, 0, 10);
    $int = time() - $time;
    $str = '';
    if ($int <= 2){
        $str = sprintf('刚刚', $int);
    }elseif ($int < 60){
        $str = sprintf('%d秒前', $int);
    }elseif ($int < 3600){
        $str = sprintf('%d分钟前', floor($int / 60));
    }elseif ($int < 86400){
        $str = sprintf('%d小时前', floor($int / 3600));
    }elseif ($int < 2592000){
        $str = sprintf('%d天前', floor($int / 86400));
    }else{
        $str = date('Y-m-d H:i:s', $time);
    }
    return $str;
}

//判断两天是否是同一天
function judgeDiffDays($last_date,$this_date)
{
    if(($last_date['year'] === $this_date['year']) && ($this_date['yday'] === $last_date['yday'])){
        return FALSE;
    }else{
        return TRUE;
    }
}

//随机获取字符串
function getRandStr($num=6)
{  
    $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';  
    $randStr = str_shuffle($str);//打乱字符串  
    $rands= substr($randStr,0,$num);//substr(string,start,length);返回字符串的一部分  
    return $rands;  
} 

//生成订单号
function generateRandNumbers($scode,$val="",$num=3)
{
    return $val.time().$scode.getRandStr($num);
}

//检测坐标的距离
function judgedistance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;
    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;
    return round(($miles ? ($km * 0.621371192) : $km),1);
}

//生成原始的二维码非文件图片
function createQrcodeOriginal($value=''){  
        $errorCorrectionLevel = 'L';    //容错级别   
        $matrixPointSize = 5;           //生成图片大小    
        //生成二维码图片  
        $QR = QRcode::png($value,false,$errorCorrectionLevel, $matrixPointSize, 2);  
        exit();
}  
  // 生成不带logo的二维码图片文件 
function createQrcodeFile($value='',$file='qrcode'){            
    $errorCorrectionLevel = 'L';    //容错级别   
    $matrixPointSize = 5;           //生成图片大小              
    //生成二维码图片  
    $filename = $file.'/qrcode.png'; 
    if(file_exists($filename)) unlink ($filename);
    QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);            
    $QR = $filename;                //已经生成的原始二维码图片文件    
      
    $QR = imagecreatefromstring(file_get_contents($QR));            
        //输出图片    
    imagepng($QR, $filename);    
    imagedestroy($QR);  
    return '/'.$filename;     
}  
    //生成带logo的二维码图片文件
function createLogoQrcode($value='',$file='qrcode',$logo='qrcode/logo.jpg'){    
    $errorCorrectionLevel = 'H';    //容错级别    
    $matrixPointSize = 6;           //生成图片大小    
        //生成二维码图片  
    $filename = $file.'/qrcode.png';
    QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);    
    $QR = $filename;            //已经生成的原始二维码图    
    if (file_exists($logo)) {     
        $QR = imagecreatefromstring(file_get_contents($QR));        //目标图象连接资源。  
        $logo = imagecreatefromstring(file_get_contents($logo));    //源图象连接资源。  
        $QR_width = imagesx($QR);           //二维码图片宽度     
        $QR_height = imagesy($QR);          //二维码图片高度     
        $logo_width = imagesx($logo);       //logo图片宽度     
        $logo_height = imagesy($logo);      //logo图片高度     
        $logo_qr_width = $QR_width / 4;     //组合之后logo的宽度(占二维码的1/5)  
        $scale = $logo_width/$logo_qr_width;    //logo的宽度缩放比(本身宽度/组合后的宽度)  
        $logo_qr_height = $logo_height/$scale;  //组合之后logo的高度  
        $from_width = ($QR_width - $logo_qr_width) / 2;   //组合之后logo左上角所在坐标点  
            
        //重新组合图片并调整大小  
        /* 
        *  imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中 
        */  
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);   
    }     
    //unlink ($filename);
    //输出图片   
    // file_exists($QR);
    if(file_exists($filename)) unlink ($filename); 
    imagepng($QR, $file.'/qrcode.png');
    imagedestroy($QR);  
    imagedestroy($logo);
    return '/'.$file.'/qrcode.png';     
}  

        /**
     * 生成二维码
     * @param  string  $url  url连接
     * @param  integer $size 尺寸 纯数字
     */
function createQrcode($value, $logo = 'qrcode/logo.jpg', $url='', $size=4,$errorCorrectionLevel = 'L', $matrixPointSize = 5, $filename = 'qrcode/qrcode.png'){
        // $errorCorrectionLevel = 'L';    //容错级别   
        // $matrixPointSize = 5;           //生成图片大小    
          
        //生成并下载二维码图片  
        // $filename = 'qrcode/qrcode.png';  
        QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);   
        
        $QR = $filename;                //已经生成的原始二维码图片文件        
        //$QR = imagecreatefromstring(file_get_contents($QR));    
        //添加Logo
        if (file_exists($logo)) {     
            $QR = imagecreatefromstring(file_get_contents($QR));        //目标图象连接资源。  
            $logo = imagecreatefromstring(file_get_contents($logo));    //源图象连接资源。  
            $QR_width = imagesx($QR);           //二维码图片宽度     
            $QR_height = imagesy($QR);          //二维码图片高度     
            $logo_width = imagesx($logo);       //logo图片宽度     
            $logo_height = imagesy($logo);      //logo图片高度     
            $logo_qr_width = $QR_width / 4;     //组合之后logo的宽度(占二维码的1/5)  
            $scale = $logo_width/$logo_qr_width;    //logo的宽度缩放比(本身宽度/组合后的宽度)  
            $logo_qr_height = $logo_height/$scale;  //组合之后logo的高度  
            $from_width = ($QR_width - $logo_qr_width) / 2;   //组合之后logo左上角所在坐标点  
              
            //重新组合图片并调整大小  
            /* 
             *  imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中 
             */  
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);   
        }     
        //输出图片    
        imagepng($QR, $filename);    
        imagedestroy($QR);
        imagedestroy($logo);  
        return '/'.$filename;  

        //直接输出不下载
        // if (strpos($url, 'http')===false) {
        //     $url='http://'.$url;
        // }
        // QRcode::png($url,false,QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000);
        // exit();
}


function getResourcesLove($dir){

    $handle=opendir($dir.".");
 	$array_file = array();
    while (false !== ($file = readdir($handle)))
	{
	 	if ($file != "." && $file != "..") {
		$array_file[]['name'] = $file; //输出文件名
        }
    }

	return $array_file;
}

//生成密钥
function generatingKey($value,$rand='',$code='super')
{
    $rand = MD5($rand);
    return md5($code.$value.$rand);
}


//获取菜单子列表
function getChildManageMenu($id='')
{
	$data = Db::name('manage_menu')->where(array('Pid'=>$id,'State'=>1))->select();
	foreach ($data as $d => $a) {
		$data[$d]['Url'] = $a['Ctrl'].'/'.$a['Alt'];
	}
	return $data;
}

//无限递归分类菜单
function getCategoryInfinite($data,$pid=0,$level=1)
{
    static $arr = array();
    $tl = ''; 
    foreach($data as $d => $a){
        if($a['Pid'] == $pid){
            $a['Level'] = $level;
            $a['Name'] = $tl.$a['Name'];
            $arr[] = $a;
            unset($data[$d]);
            getCategoryInfinite($data,$a['id'],$level+1);
        }
    }
    return $arr;
    
}

//引用获取地区列表
function getRegionTree($data){
    //第一步 构造数据
    $items = array();
    $tree = array();
    foreach($data as $value){
        $items[$value['id']] = $value;
    }
    //第二部 遍历数据 生成树状结构
    $tree = array();
    foreach($items as $key => $item){
        if(isset($items[$item['parent_id']])){
            $items[$item['parent_id']]['son'][] = &$items[$key];
        }else{
            $tree[] = &$items[$key];
        }
    }
    return $tree;
}

//获取所有的子分类的ID
function getAllCategoryChild($data,$id){
    $arr = array();
    foreach($data as $v){
        if($v['Pid'] == $id){
            $arr[] = $v['id'];
            $arr = array_merge($arr,getAllCategoryChild($data,$v['id']));
        };
    };
    return $arr;
}

//获取分类顶级ID
function getCategoryHighest($data,$key='',$val='message')
{
	try{
		$arr = array();
		// foreach($data as $d => $a){
		// 	$arr[$a['id']] = $a['Pid'];
		// }
        $arr = array_column($data,'Pid','id');
		while($arr[$key]) {
				$key = $arr[$key];  
		}
		return $key;
	}
	catch(\Exception $e){
        $e->getMessage();
        return  false;
	}
    
}


//审核状态
function getAllToexamine($val){
    if($val == 1) 
    return '已审核';
    return '待审核';
}
//留言审核状态
function getMessageToexamine($val){
    if($val == 1) 
    return '已审核';
    if($val == 2)
    return '待审核';
    if($val == 3)
    return '未读';
}
//反馈处理审核状态
function getFeedbackToexamine($val){
    if($val == 1) 
    return '已读';
    if($val == 2)
    return '待审核';
    if($val == 3)
    return '未读';
}

//支付状态
function getSuccessFailur($val){
    if($val == 1) 
    return '成功';
    return '异常';
}

// ===========================================用户模块==========================================
//判断名片信息完整度
function judgeUserCardInfo($uid)
{
    $where['User_id'] = ['=',$uid];
    if(!$re = Db::name('user_card')->where($where)->find())
    return false;
    if(!$re['Phone'] || $re['Phone'] == '' || !$re['Realname'] || $re['Realname'] == '')
    return false;
    return true;
}
//获取用户基本信息
function getUserInfo($uid,$val='Username')
{
    if($val) return Db::name('user')->where(array('User_id'=>$uid))->value($val);
    return Db::name('user')->where(array('User_id'=>$uid))->find();
}
//获取用户基本信息
function getUserOpenidInfo($oid,$val='Username')
{
    if($val) return Db::name('user')->where(array('openid'=>$oid))->value($val);
    return Db::name('user')->where(array('openid'=>$oid))->find();
}

//获取用户Card信息
function getUserCardInfo($uid,$val='')
{
    $where['User_id'] = ['=',$uid];
    if($val) return Db::name('user_card')->where($where)->value($val);
    return Db::name('user_card')->where($where)->find();
}

//获取用户Poster信息
function getUserPosterInfo($uid,$where=array('State'=>1),$field='id,Url',$order='Sort desc,Addtime asc')
{
    if($re = Db::name('user_poster')->where(array('User_id'=>$uid))->where($where)->order($order)->field($field)->select()){
        foreach($re as $r => $e){
            $imgInfo   =   getimagesize($e['Url']); 
            $re[$r]['Width'] = $imgInfo[0];
            $re[$r]['Height'] = $imgInfo[1];
        }
    }
    return $re;
}

//定义红包寄语
function getRedenvelopeBlessings()
{
    $arr = array(
            'selected'=>'好兆头',
            'selecList'=>array('好兆头'=>[
                    '猪年猪事顺利！','万事如意，猪事顺意！','猪笼入水，好运连连！','二零一九，大展宏图！','步步高升，财源广进！','步步高升，万事顺意！','开业大吉，生意兴隆！','财源广进，日进斗金！','友人广聚，财源滚滚！','事业蒸蒸日上，更上一层楼！','祝大展宏图，财运亨通！','祝前程似锦，辉煌腾达！','祝你身体健康，天天开心！','祝新婚快乐，百年好合！','祝早日脱单，迎娶白富美！','祝蒙的全对，逢考必过！'
                ],
                '见面认识'=>[
                    '很高兴认识大家！','很高兴认识你！','认识你我很高兴！','见到您很荣幸！','初次见面，请多多关照！','谢谢您对我的关照！','谢谢你为我做的一切！','谢谢你为我做的一切！'
                ],
                '节日快乐'=>[
                    '三八女王节快乐！','儿童节快乐！','劳动节快乐！','端午节快乐！','情人节快乐！','中秋节快乐！','圣诞快乐！'
                ]
            )
        );
    return $arr;
}


//获取用户剩余红包信息
function getUserRedenvelopesInfo($uid,$val='')
{
    $where['User_id'] = ['=',$uid];
    $where['Blance'] = ['>',0];
    $order = 'Addtime desc';
    if($re = Db::name('redenvelopes')->where($where)->order($order)->select())
    return $re;
    return false;
}

//获取用户被领取的红包记录
function getUserRedenvelopesCodeList($uid,$val='Redenvelopes_id')
{
    $where['User_id'] = ['=',$uid];
    $where['State'] = ['=',1];
    $order = 'Addtime desc';
    $re = Db::name('redenvelopes')->where($where)->field($val)->order($order)->select();
    if($re && is_array($re)){
        $ids = array_column($re,$val);
	    return implode(',',$ids);
    }
    return false;
}

//获取用户点赞数
function getUserGiveUpList($uid='')
{
    $where['Giv_user_id'] = ['=',$uid];
    return Db::name('giveup_user')->where($where)->select();
}

//获取用户Region信息
function getUserRegionInfo($id,$val='name')
{
    if($val) return Db::name('region')->where(array('id'=>$id))->value($val);
    return Db::name('region')->where(array('id'=>$id))->find();
}
//获取用户Hobby信息
function getUserHobbyInfo($id,$val='name')
{
    if($val) return Db::name('hobby')->where(array('id'=>$id))->value($val);
    return Db::name('hobby')->where(array('id'=>$id))->find();
}
//获取用户Industry信息
function getUserIndustryInfo($id,$val='name')
{
    if($val) return Db::name('industry')->where(array('id'=>$id))->value($val);
    return Db::name('industry')->where(array('id'=>$id))->find();
}
//获取用户Campus信息
function getUserCampusInfo($id,$val='name')
{
    if($val) return Db::name('campus')->where(array('id'=>$id))->value($val);
    return Db::name('campus')->where(array('id'=>$id))->find();
}

//获取用户Friend信息
function getUserFriendInfo($uid,$val='')
{
    if($val){
         $arr = Db::name('user_friend')->where(array('User_id'=>$uid))->value($val);
         return json_decode($arr);
    }
    return Db::name('user_friend')->where(array('User_id'=>$uid))->find();
}

//获取用户Stranger信息
function getUserStrangerInfo($uid)
{
    $vn = getUserFriendInfo($uid);
    $friends = json_decode($vn['Friend_ids']);
    $stranger = array();
    foreach($friends as $fr){
        if($ot_friend = getUserFriendInfo($fr,'Friend_ids')){
            if(!in_array($uid,$ot_friend)){
                $stranger = array_push($fr,$stranger);
            }
        }
    }
    return $stranger;
}

//用户缘分值检测
function getMatchingMarginValue($uid,$mid)
{
    $Fate = 0;
     $field = "a.Username,a.User_id,a.Head_portrait,a.Land_time,a.Addtime,b.Introduce,b.Phone,b.Wechat,b.Realname,b.Card_portrait,b.Card_address,b.Company,b.Occupation,c.Campus,c.Industrys,c.Hobbys,c.Age,c.Demand,c.Languages,c.Gender,c.Marriage,c.Position,c.Longitud,c.Latitude,c.Hometowns,c.Locations";
    $re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.User_id'=>$uid))->Field($field)->find();
    $rb = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.User_id'=>$mid))->Field($field)->find();
    if($re && $rb){
                if($re['Hometowns'] && $rb['Hometowns']){//同乡
                    $Hometowns1 = json_decode($re['Hometowns'],true);
                    $Hometowns2 = json_decode($rb['Hometowns'],true);
                    if(is_array($Hometowns1) && is_array($Hometowns2)){
                        for($i=0;$i<count($Hometowns1);$i++){
                            for($t=0;$t<count($Hometowns2);$t++){
                                if($Hometowns1[$i]['province'] == $Hometowns2[$t]['province'] && $Hometowns1[$i]['city'] == $Hometowns2[$t]['city']){
                                    $Fate += 10;
                                    break;
                                }
                            }
                        }
                    }
                }
                if($re['Locations'] && $rb['Locations']){//同城
                        $Locations1 = json_decode($re['Locations'],true);
                        $Locations2 = json_decode($rb['Locations'],true);
                        if(is_array($Locations1) && is_array($Locations2)){
                            for($i=0;$i<count($Locations1);$i++){
                                for($t=0;$t<count($Locations2);$t++){                               
                                if($Locations1[$i]['province'] == $Locations2[$t]['province'] && $Locations1[$i]['city'] == $Locations2[$t]['city']){
                                    $Fate += 10;
                                    break;
                                }
                            }
                        }
                    }
                }
                if($re['Campus'] && $rb['Campus']){//同校
                    $Campus1 = explode(',', $re['Campus']);
                    $Campus2 = explode(',', $rb['Campus']);
                    if(is_array($Campus1) && is_array($Campus2)){                       
                        $Campus = array_intersect($Campus1,$Campus2);
                        if($Campus){
                            $Fate += 10;
                        }
                    }
                }
                if($re['Demand'] && $rb['Demand']){//同需求
                    $Demand1 = explode(',', $re['Demand']);
                    $Demand2 = explode(',', $rb['Demand']);
                    if(is_array($Demand1) && is_array($Demand2)){                       
                        $Demands = array_intersect($Demand1,$Demand2);
                        if($Demands){
                            $Fate += 10;
                        }
                    }
                }
                if($re['Languages'] && $rb['Languages']){//同语言
                    $Languages1 = explode(',', $re['Languages']);
                    $Languages2 = explode(',', $rb['Languages']);
                    if(is_array($Languages1) && is_array($Languages2)){                       
                        $Languages = array_intersect($Languages1,$Languages2);
                        if($Languages){
                            $Fate += 10;
                        }
                    }
                }
                if($re['Hobbys'] && $rb['Hobbys']){//同趣
                    $Hobbys1 = explode(',', $re['Hobbys']);
                    $Hobbys2 = explode(',', $rb['Hobbys']);
                    if(is_array($Hobbys1) && is_array($Hobbys2)){                       
                        $Hobbys = array_intersect($Hobbys1,$Hobbys2);
                        if($Hobbys){
                            $count = count($Hobbys);
                            if($count>5) 
                            $count = 5;
                            $Fate += 2*$count;
                        }
                    }
                }
                if($re['Age'] && $rb['Age']){//同龄
                    if($re['Age'] < $rb['Age']+2 && $re['Age']>$rb['Age']-2){
                        $Fate += 10;
                    }
                }
                if($re['Gender'] && $rb['Gender']){//异性
                    if($re['Gender'] != $rb['Gender']){
                        $Fate += 10;
                    }
                }
                if($re['Marriage'] && $rb['Marriage']){//婚恋状况
                    if($re['Marriage'] == $rb['Marriage']){
                        $Fate += 10;
                    }
                }
                if($re['Longitud'] && $re['Latitude'] && $rb['Longitud'] && $rb['Latitude']){
                    $distance = judgedistance($re['Longitud'],$re['Latitude'],$rb['Longitud'],$rb['Latitude']);
                    if($distance <3){
                        $Fate += 10;
                    }
                }
    }
    return $Fate;
}

//查询对方是否好友
function judgeUserFriend($uid,$mid)
{
    $vn = getUserFriendInfo($mid,'Friend_ids');
	$vm = getUserFriendInfo($mid,'Blacklist_ids');
    if(in_array($uid,$vn) && !in_array($uid,$vm))
    return true;
    return false;
}

//查询对方是否黑名单
function judgeUserBlacklist($uid,$mid)
{
    $vn = getUserFriendInfo($mid,'Blacklist_ids');
    if(in_array($uid,$vn))
    return true;
    return false;
}
//查询对方是否已被点赞
function judgeUserGiveUpState($uid,$mid)
{
    $where['User_id'] = ['=',$uid];
    $where['Giv_user_id'] = ['=',$mid];
    if($re = Db::name('giveup_user')->where($where)->find())
    return true;
    return false;
}


// ===========================================红包模块==========================================、
//获取红包被领取的记录
function gteCountRedenvelopesCodeSingle($rid,$page=1,$pagesize=8)
{
    $count = 0;
    $re = array();
    $field = 'a.User_id';
    $where['a.Redenvelopes_id'] = ['in',$rid];
    $order = 'a.User_id';
    try {
        // （返回所有字段，服务器数据库不支持）
        $re = Db::name('redenvelopes_code')->alias('a')->group('a.User_id')->join('user b','b.User_id=a.User_id')->where($where)->order($order)->page($page)->limit($pagesize)->select();
        $count = count( Db::name('redenvelopes_code')->alias('a')->group('a.User_id')->join('user b','b.User_id=a.User_id')->where($where)->select());

    } catch (Exception $e) {
        $re = Db::name('redenvelopes_code')->alias('a')->distinct(true)->field($field)->join('user b','b.User_id=a.User_id')->where($where)->order($order)->page($page)->limit($pagesize)->select();
        $count = count( Db::name('redenvelopes_code')->alias('a')->distinct(true)->field($field)->join('user b','b.User_id=a.User_id')->where($where)->select());
        if($re){
            foreach($re as $r=>$e){
            $uf = getUserInfo($e['User_id'],'');
            $re[$r]['Username'] = $uf['Username'];
            $re[$r]['Head_portrait'] = $uf['Head_portrait'];
            }
        }
    }
    $arr = [
        'count'=>$count,
        'list'=>$re
    ];
    return $arr;
}


//查询缘分红包规则
function judgeRedenvelopesFateRule($rid)
{
    $where['Redenvelopes_id'] = ['=',$rid];
    return Db::name('user_fate_redenvelopes_rule')->where($where)->find();
}


//查询指定红包是否还可领取红包
function judgeUserAppointRedenvelopesCode($uid,$rid)
{
    $where['User_id'] = ['=',$uid];
    $where['Redenvelopes_id'] = ['=',$rid];
    return Db::name('redenvelopes_code')->where($where)->count();
}

//查询用户是否还可领取红包
function judgeUserWhenRedenvelopesCode($uid,$where,$order,$field)
{
    $arr = array();
    if(!$re = Db::name('redenvelopes')->where($where)->order($order)->field($field)->select())
    return $arr;
    $db = Db::name('redenvelopes_code');
    foreach($re as $r=>$e){
        $count = $db->where(array('User_id'=>$uid,'Redenvelopes_id'=>$e['Redenvelopes_id']))->count();
        if($count == 0){
            $arr['num'] = $count;
            $arr['msg'] = $e['Message'];
            $arr['rid'] = $e['Redenvelopes_id'];
            return $arr;
        }
    }
    foreach($re as $r=>$e){
        $count = $db->where(array('User_id'=>$uid,'Redenvelopes_id'=>$e['Redenvelopes_id']))->count();
        if($count == 1){
            $arr['num'] = $count;
            $arr['msg'] = $e['Message'];
            $arr['rid'] = $e['Redenvelopes_id'];
            return $arr;
        }
    }
    return $arr;
}

//查询用户是否还可领取红包
function judgeUserWhetherRedenvelopesCode($uid,$mid,$num = 0)
{
    if($ids = getUserRedenvelopesCodeList($mid)){
        $ids = "'".implode("',\n'",explode(",",str_replace("\r",'',$ids)))."'";
        $t = time();
        $start_time = mktime(0,0,0,date('m',$t),date('d',$t),date('Y',$t));//当天开始时间
        $end_time = mktime(23,59,59,date('m',$t),date('d',$t),date('Y',$t));//当天结束时间
        $where = 'User_id = "'.$uid.'"';
        $where .= ' and Addtime >'.$start_time;
        $where .= ' and Addtime <='.$end_time;
        $where .= ' and Redenvelopes_id in('.$ids.')';
        $sql = 'select count(Redenvelopes_id) ,Redenvelopes_id from super_redenvelopes_code where '.$where.' group by Redenvelopes_id having count(Redenvelopes_id)>'.$num.' order by count(Redenvelopes_id) desc';
        if($re = Db::query($sql))
        return $re;
    }
    return false;
}

//查询用户是否存在可用红包并随机获取一条
function judgeUserRedenvelopesRand($uid='')
{
    $where['User_id'] = ['=',$uid];
    $where['State'] = ['=',1];
    $where['Nums'] = ['>',0];
    $where['Blance'] = ['>',0];
    if($re = Db::name('redenvelopes')->where($where)->orderRaw('rand()')->find())
    return $re;
    return false;
}

//查询用户是否存在可用红包
function judgeUserRedenvelopes($uid='')
{
    $where['User_id'] = ['=',$uid];
    $where['State'] = ['=',1];
    $where['Blance'] = ['>',0];
    $order = 'Addtime desc';
    if($re = Db::name('redenvelopes')->where($where)->order($order)->select())
    return $re;
    return false;
}

//查询缘分红包充值记录
function getRedenvelopesRechargeInfo($reid)
{
    $where['Recharge_id'] = ['=',$reid];
    return Db::name('user_recharge_record')->where($where)->find();
}

//统计用户发红包记录
function getRedenvelopesUserCount($uid)
{
    $where['User_id'] = ['=',$uid];
    $where['State'] = ['=',1];
    return Db::name('redenvelopes')->where($where)->count();
}
//统计用户收红包记录
function getRedenvelopesCodeUserCount($uid)
{
    $where['User_id'] = ['=',$uid];
    return Db::name('redenvelopes_code')->where($where)->count();
}
//统计当前红包被领取记录
function getRedenvelopesCodeCount($rid)
{
    $where['Redenvelopes_id'] = ['=',$rid];
    return Db::name('redenvelopes_code')->where($where)->count();
}
//统计当前红包剩余数量
function getRedenvelopesListCount($rid)
{
    $where['Redenvelopes_id'] = ['=',$rid];
    return Db::name('redenvelopes_list')->where($where)->count();
}
//统计用户发红包总额
function getRedenvelopesSum($uid='')
{
    $where['User_id'] = ['=',$uid];
    $where['State'] = ['=',1];
    return Db::name('redenvelopes')->where($where)->sum('Amount');
}
//统计收红包总额
function getRedenvelopesCodeSum($uid)
{
    $where['User_id'] = ['=',$uid];
    return Db::name('redenvelopes_code')->where($where)->sum('Amount');
}

//分页获取用户收发红包记录
function getRedenvelopesReceiveList($table,$where,$order = 'Addtime desc',$page = 1, $pagesize = 999999,$file = '*')
{
    return Db::name($table)->where($where)->order($order)->field($file)->page($page)->limit($pagesize)->select();

}

//获取某条红包记录信息
function getRedenvelopesInfo($rid,$val='')
{
    $where['Redenvelopes_id'] = ['=',$rid];
    if($val) return Db::name('redenvelopes')->where($where)->value($val);
    return Db::name('redenvelopes')->where($where)->find();
}

//根据系统设置生成红包
function generateAppointRedenvelope($total,$num,$min=0.1)
{      
    try{     
        $where['State'] = ['=',1];
        $arr = array();
        if(!$re = Db::name('fate_value')->where($where)->select()){
            foreach($re as $r=>$e){
                $amount = $total*($e['Value']/100);
                $amount = round($amount,2);
                //$amount = sprintf("%.2f", $amount);
                // $amount = sprintf("%.2f",substr(sprintf("%.3f", $amount), 0, -2)); 
                $arr[$r] = array(
                    'key' => $e['Fate'],
                    'value' => $amount,
                );
            }
        }else{
            require_once EXTEND_PATH."RedAlgor/RedAlgor.php";
	        $RedAlgor = new \RedAlgor($total,$num,$min);
            $result = $RedAlgor->handle();
            for($i = 0; $i < count($result['items']); $i++){
                $arr[$i]['key'] = 0;
                $arr[$i]['value'] = $result['items'][$i];
            }
        }
        return $arr;
    }catch(Exception $e){
        return false;
    }
}

// ===========================================社区模块==========================================
//查询用户是否有新留言
function judgeUserNewMessage($uid,$val='message')
{
    $where['State'] = ['=',3]; 
    $where['pid'] = ['=',0]; 
    $where['User_id'] = ['<>',$uid]; 
    $where['Giv_user_id'] = ['=',$uid]; 
    return Db::name($val)->where($where)->count();
}

//查询用户是否有新回复
function judgeUserNewReply($uid,$val='message')
{
    $where['State'] = ['=',3]; 
    $where['pid'] = ['<>',0]; 
    $where['User_id'] = ['<>',$uid]; 
    $where['Giv_user_id'] = ['=',$uid]; 
    return Db::name($val)->where($where)->count();
}

//查询指定留言是否有回复
function judgeCommunityReply($id,$val='message')
{
    $where['State'] = ['<>',2]; 
    $where['pid'] = ['=',$id]; 
    return Db::name($val)->where($where)->select();
}

//循环遍历获取评论列表
function getCommunityReplyList($pid=0, $val, &$arr=array(), $level=0,$where=array(), $order='Addtime desc', $page=1, $pagesize=99999) {
    try{
        static $i = 0;
        $level += 1; //初始为1级评论
        $re = Db::name($val)->where(array('pid'=>$pid))->where($where)->order($order)->page($page)->limit($pagesize)->select();
        foreach ($re as $k => $v) {
            $arr[$i]['Level'] = $level; //评论层级
            $arr[$i]['User_id'] = $v['User_id'];
            $arr[$i]['Giv_user_id'] = $v['Giv_user_id'];
            $arr[$i]['id'] = $v['id'];
            $arr[$i]['Pid'] = $v['Pid']; //此条评论的父id
            $arr[$i]['Content'] = $v['Content'];
            $arr[$i]['Addtime'] = date('Y-m-d h:i:s',$v['Addtime']);
            $arr[$i]['State'] = $v['State'];
            $i++;
            getCommunityReplyList($v['id'], $val, $arr, $level, $where, $order, $page, $pagesize);
        }
        return $arr;
    }catch(Exception $e){
        return $e->getMessage();
    }
}
//引用深层遍历留言
function getMessageTree($data){
    //第一步 构造数据
    $items = array();
    $tree = array();
    foreach($data as $value){
        $items[$value['id']] = $value;
    }
    //第二部 遍历数据 生成树状结构
    $tree = array();
    foreach($items as $key => $item){
        if(isset($items[$item['Pid']])){
            $items[$item['Pid']]['son'][] = &$items[$key];
        }else{
            $tree[] = &$items[$key];
        }
    }
    return $tree;
}

//无限递归获取评论列表
function getCommunityReplyInfinite($data,$pid=0,$level=1)
{
    static $arr = array();
    $tl = ''; 
    foreach($data as $d => $a){
        if($a['Pid'] == $pid){
            $a['Level'] = $level;
            $arr[] = $a;
            unset($data[$d]);
            getCommunityReplyInfinite($data,$a['id'],$level+1);
        }
    }
    return $arr;
    
}


// ===========================================扩展==========================================
//过滤参数
function judgeFilterSql()
{
    require_once EXTEND_PATH."FilterSql/Sqlsafe.php";
	$pdo_buk = new \FiterSqlsafe();
}

//写入操作日志
function writeCretLog($content,$dir ='log.txt',$path = '../log')
{
    // $position = strrpos($filename,'/');
	// $path = substr($filename,0,$position);
	// if(!file_exists($path)){
	// 	mkdir($path,0777,true);
    // }
    if(!is_dir($path)) mkdir(iconv("UTF-8", "GBK", $path),0777,true);
    $file = $path.'/'.$dir;
    $content = date('Y/m/d H:i',time()).' '.$content."\n";
    file_put_contents($file, $content,FILE_APPEND);
}

//获取配置
function getWxconfig($val)
{
    $wxconfig = Config($val);
    return $wxconfig;
}
//格式化日期
function getFormatTime($val='')
{
    return date('Y/m/d H:i:s',$val);
}

// 删除本地图片或文件
function deleFile($pic){
    try {
        if(!$pic)
        return array('success' =>0 ,'errors'=>'请传递文件');
        if(!file_exists(substr($pic, $url)))
        return array('success' =>404 ,'errors'=>'文件不存在');
        if(unlink(substr($pic, $url)))
        return array('success' =>1 ,'errors'=>'删除文件成功');
    } catch (Exception $e) {
        return $e->getMessage();
    } finally {
    return false;
    
    }
}